<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>批量压缩处理</title>

	<!-- 引入样式 -->
	<link rel="stylesheet" href="/webjars/element-ui/lib/theme-chalk/index.css">

	<link rel="stylesheet" href="../style/css/common.css">
	<link rel="stylesheet" href="../style/css/batch.css">

</head>

<body>
	<div id="app">
		<el-container style="height: 100%;">
			<el-header>
				<el-upload class="upload-btn" ref="fileUpload" action="url" :auto-upload="false" :multiple="true"
						   accept="image/*" :show-file-list="false" :on-change="selectImage">
					<el-button slot="trigger" plain size="medium">选择文件</el-button>
				</el-upload>

				<el-button plain size="medium" type="danger" style="float:right" @click="clearTable"
						   :disabled="tableData.length == 0">全部清除</el-button>
			</el-header>
			<el-main>
				<el-table v-loading="loading" ref="fileTable" size="mini" :data="tableData" :height="tableHeight" border
						  style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}"
						  @selection-change="selectRowHandle">
					<el-table-column type="selection" width="39"></el-table-column>
					<el-table-column prop="fileName" sortable label="文件名称"></el-table-column>
					<el-table-column prop="fileSize" sortable label="原始大小" :formatter="formatFileSize">
					</el-table-column>
					<el-table-column prop="widthAndHeight" label="原始尺寸"></el-table-column>
					<el-table-column prop="statusName" sortable label="压缩状态"></el-table-column>
					<el-table-column prop="compressSize" sortable label="压缩后大小" :formatter="formatFileSize">
					</el-table-column>
					<el-table-column prop="compressWidthAndHeight" label="压缩后尺寸"></el-table-column>
					<el-table-column prop="compressRate" sortable label="压缩率" :formatter="formatRate"></el-table-column>
				</el-table>
			</el-main>
			<el-footer height="170px">
				<el-row>
					<el-col :span="18">
						<el-form ref="form" :model="param" label-width="100px" label-position="left">
							<el-form-item label="压缩模式">
								<el-radio-group v-model="param.model">
									<el-radio :label="1">默认模式</el-radio>
									<el-radio :label="2">质量调整</el-radio>
									<el-radio :label="3">尺寸调整</el-radio>
									<el-radio :label="4">自定义</el-radio>
								</el-radio-group>
							</el-form-item>

							<el-form-item v-if="param.model==2" label="图片质量">
								<el-slider v-model="param.quality" :min="10" style="width:400px"></el-slider>
							</el-form-item>
							<el-form-item v-if="param.model==3" label="图片尺寸">
								<el-slider v-model="param.scale" :min="10" style="width:400px"></el-slider>
							</el-form-item>

							<el-form-item v-if="param.model==4" label="图片质量">
								<el-slider v-model="param.quality" :min="10" style="width:400px"></el-slider>
							</el-form-item>
							<el-form-item v-if="param.model==4" label="图片尺寸">
								<el-row>
									<el-col :span="13">
										<el-slider v-model="param.scale" :min="10" :disabled="param.diySize">
										</el-slider>
									</el-col>
									<el-col :span="1">&nbsp;</el-col>
									<el-col :span="5">
										<el-checkbox v-model="param.diySize">自定义宽高</el-checkbox>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="6">
										<el-input v-model="param.width" type="number" size="small" placeholder="请输入宽度"
												  :disabled="!param.diySize">
											<template slot="prepend">宽</template>
										</el-input>
									</el-col>
									<el-col :span="1">&nbsp;</el-col>

									<el-col :span="6">
										<el-input v-model="param.height" type="number" size="small" placeholder="请输入高度"
												  :disabled="!param.diySize">
											<template slot="prepend">高</template>
										</el-input>
									</el-col>
									<el-col :span="1">&nbsp;</el-col>
									<el-col :span="5">
										<el-checkbox v-model="param.force" :disabled="!param.diySize">强制拉伸</el-checkbox>
									</el-col>
								</el-row>
							</el-form-item>
						</el-form>
					</el-col>
					<el-col :span="6">
						<el-button type="primary" @click="doCompress" :disabled="finished">开始压缩</el-button>
						<el-button type="primary" @click="download" :disabled="!finished">下载</el-button>
					</el-col>
				</el-row>
			</el-footer>
		</el-container>
	</div>
</body>
<script src="/webjars/vue/vue.min.js"></script>
<script src="/webjars/element-ui/lib/index.js"></script>
<script src="/webjars/axios/dist/axios.min.js"></script>
<script src="/webjars/jszip/dist/jszip.min.js"></script>
<script src="/webjars/file-saver/dist/FileSaver.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>

<script src="../js/utils.js"></script>

<script src="../js/ws.js"></script>

<script src="../js/request.js"></script>
<script src="../js/image-api.js"></script>
<script type="text/javascript">
	new Vue({
		el: '#app',
		data: function () {
			return {
				loading: false,
				finished: false,
				tableHeight: 400,
				tableData: [],
				selectRows: [],
				param: {
					model: 1, // 压缩模式：1，默认模式，2，质量调整，3，尺寸调整，4，自定义
					quality: 80, //图片质量
					scale: 80, //图片尺寸
					diySize: false,
					width: null,
					height: null,
					force: false, //是否强制拉伸
				},
			};
		},
		mounted() {
			//  this.tableHeight = document.querySelector("#app").clientHeight -100;
			//  console.info(this.tableHeight);

			//发起连接
			ws.connect("/queueServer", () => {

				//定义通知
				ws.subscribe(`/user/${ws.sessionId}/compress/detail`, (data) => {
					console.info(data);
					let item = this.tableData.find(i => i.fileName == data.fileName);
					if (item) {
						item.statusName = data.statusName;
						item.widthAndHeight = data.widthAndHeight;
						item.compressSize = data.compressSize;
						item.compressWidthAndHeight = data.compressWidthAndHeight;
						item.compressRate = data.compressRate;
						item.downloadUrl = data.downloadUrl;
					};
				});


				//定义通知
				ws.subscribe(`/user/${ws.sessionId}/compress/notify`, (data) => {
					this.$notify(data);
					if (data.finished) {
						this.finished = true;
					}
				});
			})

			window.onbeforeunload = () => {
				ws.sendMessage("/clearFile", {
					content: "关闭时清除文件"
				});
			}

			// ws.sendMessage("/queue", { name: "发送消息" });
		},
		methods: {
			selectRowHandle(val) {
				this.selectRows = val
			},
			clearTable() {
				if (this.selectRows.length == 0) {
					this.$confirm('确认全部清除？')
						.then(_ => {
							this.finished = false;
							this.tableData = [];
						})
						.catch(_ => {});
				} else {
					let arr = this.selectRows.map(row => row.fileName);

					this.tableData = this.tableData.filter(i => arr.indexOf(i.fileName) == -1);
					this.selectRows = [];
				}
			},
			formatTooltip(val) {
				return val / 100;
			},
			formatRate(row, col, rate) {
				if (!rate) return null;

				return (rate * 100).toFixed(2) + " %";
			},
			formatFileSize(row, col, size) {
				if (!size) return null;

				if (size > 1024 * 1024) {
					return (size / (1024 * 1024)).toFixed(2) + " M";
				} else if (size > 1024) {
					return (size / 1024).toFixed(2) + " K";
				} else {
					return size.toFixed(2) + " B";
				}
			},

			selectImage(one, list) {
				this.loading = true;
				this.finished = false;

				this.$refs.fileUpload.clearFiles();

				let fileNames = this.tableData.map(row => row.fileName);


				let arr = list.filter(i => fileNames.indexOf(i.name) == -1) //
					.map((i) => {
						return new Promise((resolve, reject) => {

							this.tableData.push({
								fileName: i.name,
								fileSize: i.size,
								statusName: "待压缩",
							});

							let form = new FormData();
							form.append("sessionId", ws.sessionId);
							form.append(i.name, i.raw);

							imageApi.upload(form).then(() => resolve(i)).catch((error) => reject(
								error));
						});
					});

				if (arr.length == 0) {
					this.$notify.info({
						title: "提示",
						message: "已经存在文件名称相同的记录",
					});
					this.loading = false;
					return false;
				}

				Promise.all(arr).then(() => {
					this.$nextTick(() => {
						this.loading = false;
					});
				});
			},
			doCompress() {
				if (this.tableData.length == 0) {
					this.$notify.info({
						title: "提示",
						message: "请选择要压缩的图片",
					});
					return false;
				}

				let param = {};
				param.fileNames = this.tableData
					.filter((i) => i.statusName == "待压缩")
					.map((i) => i.fileName);

				if (param.fileNames.length == 0) return false;

				this.loading = true;
				Object.assign(param, this.param);
				param.sessionId = ws.sessionId;
				param.scale = param.scale / 100;
				param.quality = param.quality / 100;

				imageApi.batchCompress(param).then((resp) => {
					this.loading = false;
				});
			},
			download() {
				let arr = this.tableData
					.filter((i) => i.statusName == "压缩完成")
					.map((i) => {
						return {
							name: i.fileName,
							url: `${location.origin}/download?fileName=${i.fileName}&sessionId=${ws.sessionId}`
						};
					});

				if (arr.length == 0) return false;

				if (arr.length == 1) {
					download(arr[0]);
				} else {
					downloadZip(arr, "压缩后的图片.zip");
				}

				this.$notify({
					type: "success",
					title: "成功",
					message: "查看从浏览器下载记录访问压缩文件",
				});

				this.finished = false;
				this.tableData = [];

				ws.sendMessage("/clearFile", {
					content: "清除文件"
				});
			},
		},
	})
</script>

</html>